package com.password.safe.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.password.safe.constants.Constants;
import com.password.safe.dto.Messages;
import com.password.safe.service.UserService;
import com.password.safe.util.LoginObservable;
import com.password.safe.util.LoginObserver;
import com.password.safe.util.UserCache;

public class LoginController extends BaseController implements LoginObservable {
	private static Log logger = LogFactory.getLog(LoginController.class);
	private List<LoginObserver> observers;
	private UserService userService;
	
	
	private LoginController() {
		observers = new ArrayList<LoginObserver>();
	}
	
	public void doLogin(String username, String password) {
		logger.debug("enter doLogin...");
		Messages messages = Messages.getInstance();
		if (userService.checkUser(username, password)) {
			logger.debug("user is validate...");
			messages.addMessage(Constants.USERNAME, username);
			messages.addMessage(Constants.PASSWORD, password);
			UserCache.cacheUser(username, password);
			notifyLoginSuccess(messages);
    	} else {
    		logger.debug("user have input the wrong username or password");
    		notifyLoginFailed(messages);
    	}
	}
	
	public void addLoginObserver(LoginObserver observer) {
		if (observer == null) 
			throw new NullPointerException();
		if (!observers.contains(observer)) {
			observers.add(observer);
		}
	}
	
	
	public void delteLoginObserver(LoginObserver observer) {
		if (observer == null) 
			throw new NullPointerException();
		if (observers.contains(observer)) {
			observers.remove(observer);
		}
	}
	
	public void notifyLoginSuccess(Messages messages) {
		for (LoginObserver o : observers) {
			o.loginSuccess(messages);
		}
	}
	
	public void notifyLoginFailed(Messages messages) {
		for (LoginObserver o : observers) {
			o.loginFailed(messages);
		}
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
}
